from django import forms
from .models import Book, Author

class BookForm(forms.ModelForm):
    author_name = forms.CharField(label='作者', max_length=100)

    class Meta:
        model = Book
        fields = ['title', 'author_name']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk and self.instance.author:
            self.fields['author_name'].initial = self.instance.author.name

    def save(self, commit=True):
        author_name = self.cleaned_data.get('author_name')
        # 查找或创建作者
        author, created = Author.objects.get_or_create(name=author_name)
        # 关联作者到书本实例
        self.instance.author = author
        return super().save(commit)

# ... 你可能还有其他的表单，比如 AuthorForm ...
class AuthorForm(forms.ModelForm):
    class Meta:
        model = Author
        fields = ['name', 'bio'] 